package time.code.added;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;

/**
 * Description: period示例
 *
 * @author code-worker
 * @date 2021/08/22 14:03
 */
public class PeriodDemo {

    /**
     * task: 计算两个日期之间相差月数
     *       注意：这里是无法直接计算相差天数的，如2021-07-22和2021-08-22(相差0年1月0天)
     * @date 2021/8/22 14:11
     */
    public void calcDateMonths(){
        LocalDate today = LocalDate.now();
        LocalDate lastMonthToday = LocalDate.of(today.getYear(), today.getMonth().minus(1), today.getDayOfMonth());
        Period calcDateMonths = Period.between(lastMonthToday, today);
        System.out.println("今天和上个月今天相差月数: "+ calcDateMonths.getMonths());
    }

    /**
     * task: 计算两个日期相关的天数
     * @date 2021/8/22 19:50
     */
    public void calcDateDays(){
        LocalDate today = LocalDate.now();
        LocalDate lastMonthToday = LocalDate.of(today.getYear(), today.getMonth().minus(1), today.getDayOfMonth());
        long calcDateDays = today.toEpochDay() - lastMonthToday.toEpochDay();
        System.out.println("今天和上个月今天相差天数: "+calcDateDays);
    }

    public static void main(String[] args) {
        PeriodDemo demo = new PeriodDemo();
        demo.calcDateMonths();
        demo.calcDateDays();
    }

}
